
from flask import Flask, url_for, redirect, render_template, request
from flask_admin.contrib.sqla.filters import BaseSQLAFilter, FilterEqual

from wtforms import form, fields, validators
import flask_admin as admin
import flask_login as login
from flask_admin.contrib import sqla
from flask_admin import helpers, expose
from werkzeug.security import generate_password_hash, check_password_hash

from apps.models.user_model import User
from apps.models.admin_model import Users
from apps.models.moey_model import WalletMoney
from exts import db, login_manager
from flask import Blueprint
admin_tp = Blueprint('admins',__name__,)

# Define login and registration forms (for flask-login)
#定义登录和注册表单（烧瓶登录）
class LoginForm(form.Form):
    login = fields.StringField(validators=[validators.required()])
    password = fields.PasswordField(validators=[validators.required()])

    def validate_login(self, field):
        user = self.get_user()

        if user is None:
            raise validators.ValidationError('Invalid user')

        # we're comparing the plaintext pw with the the hash from the db
        #我们将明文pw与db中的哈希进行比较
        if not check_password_hash(user.password, self.password.data):
        # to compare plain text passwords use    比较纯文本密码使用
        # if user.password != self.password.data:
            raise validators.ValidationError('Invalid password')

    def get_user(self):
        return db.session.query(Users).filter_by(login=self.login.data).first()


#   lala


class RegistrationForm(form.Form):
    login = fields.StringField(validators=[validators.required()])
    email = fields.StringField()
    password = fields.PasswordField(validators=[validators.required()])

    def validate_login(self, field):
        if db.session.query(Users).filter_by(login=self.login.data).count() > 0:
            raise validators.ValidationError('Duplicate username')


# Initialize flask-login   初始化flask-login
def init_login():
    # Create user loader function    创建用户加载器功能
    @login_manager.user_loader
    def load_user(user_id):
        return db.session.query(Users).get(user_id)


# Create customized model view class    创建自定义模型视图类
class MyModelView(sqla.ModelView):
    def is_accessible(self):
        return login.current_user.is_authenticated


# Create customized index view class that handles login & registration
#创建处理登录和注册的自定义索引视图类
class MyAdminIndexView(admin.AdminIndexView):

    @expose('/')
    def index(self):
        if not login.current_user.is_authenticated:
            return redirect(url_for('.login_view'))
        return super(MyAdminIndexView, self).index()

    @expose('/login/', methods=('GET', 'POST'))
    def login_view(self):
        # handle user login   处理用户登录
        form = LoginForm(request.form)
        if helpers.validate_form_on_submit(form):
            user = form.get_user()
            login.login_user(user)

        if login.current_user.is_authenticated:
            return redirect(url_for('.index'))
        link = '<p>Don\'t have an account? <a href="' + url_for('.register_view') + '">Click here to register.</a></p>'
        self._template_args['form'] = form
        self._template_args['link'] = link
        return super(MyAdminIndexView, self).index()

    @expose('/register/', methods=('GET', 'POST'))
    def register_view(self):
        form = RegistrationForm(request.form)
        if helpers.validate_form_on_submit(form):
            user = Users()

            form.populate_obj(user)
            # we hash the users password to avoid saving it as plaintext in the db,
            # remove to use plain text:
            #我们对用户密码进行哈希处理，以避免在db中将其保存为纯文本，
            #remove使用纯文本
            user.password = generate_password_hash(form.password.data)

            db.session.add(user)
            db.session.commit()

            login.login_user(user)
            return redirect(url_for('.index'))
        link = '<p>Already have an account? <a href="' + url_for('.login_view') + '">Click here to log in.</a></p>'
        self._template_args['form'] = form
        self._template_args['link'] = link
        return super(MyAdminIndexView, self).index()

    @expose('/logout/')
    def logout_view(self):
        login.logout_user()
        return redirect(url_for('.index'))


# Flask views  烧瓶视图
@admin_tp.route('/')
def index():
    return render_template('index.html')


# Initialize flask-login  初始化flask-login
init_login()

# Create admin   创建管理员

# Add view   添加视图

# #搜索
# # Custom filter class   自定义过滤器类
# class FilterLastNameBrown(BaseSQLAFilter):
#     def apply(self, query, value, alias=None):
#         if value == '1':
#             return query.filter(self.column == "Brown")
#         else:
#             return query.filter(self.column != "Brown")
#
#     def operation(self):
#         return 'is Brown'
#
# # Customized User model admin   自定义用户模型admin
# inline_form_options = {
#     'form_label': "Info item",
#     'form_columns': ['id', 'key', 'value'],
#     'form_args': None,
#     'form_extra_fields': None,
# }
#
# class UserAdmin(sqla.ModelView):
#     action_disallowed_list = ['delete', ]
#     column_display_pk = True
#     column_list = [
#         'username',
#         'phone',
#         'email',
#     ]
#     column_default_sort = [('username', False), ('phone', False),('email', False)]  # sort on multiple columns  对多列进行排序
#     #custom filter: each filter in the list is a filter operation (equals, not equals, etc)
#     #自定义过滤器：列表中的每个过滤器都是过滤操作（等于，不等于等）
#     # filters with the same name will appear as operations under the same filter
#     #＃具有相同名称的过滤器将在同一过滤器下显示为操作
#     column_filters = [
#         FilterEqual(column=User.username, name='username'),
#         FilterLastNameBrown(column=User.username, name='username',
#                             options=(('1', 'Yes'), ('0', 'No')))
#     ]
#     inline_models = [(WalletMoney, inline_form_options), ]



def build_sample_db():
    """
    Populate a small db with some example entries.
    使用一些示例条目填充小数据库。
    """

    import string
    import random

    db.drop_all()
    db.create_all()
    # passwords are hashed, to use plaintext passwords instead:
    #password被哈希，使用明文密码代替
    # test_user = User(login="test", password="test")
    test_user = Users(login="test", password=generate_password_hash("test"))
    db.session.add(test_user)

    first_names = [
        'Harry', 'Amelia', 'Oliver', 'Jack', 'Isabella', 'Charlie','Sophie', 'Mia',
        'Jacob', 'Thomas', 'Emily', 'Lily', 'Ava', 'Isla', 'Alfie', 'Olivia', 'Jessica',
        'Riley', 'William', 'James', 'Geoffrey', 'Lisa', 'Benjamin', 'Stacey', 'Lucy'
    ]
    last_names = [
        'Brown', 'Smith', 'Patel', 'Jones', 'Williams', 'Johnson', 'Taylor', 'Thomas',
        'Roberts', 'Khan', 'Lewis', 'Jackson', 'Clarke', 'James', 'Phillips', 'Wilson',
        'Ali', 'Mason', 'Mitchell', 'Rose', 'Davis', 'Davies', 'Rodriguez', 'Cox', 'Alexander'
    ]

    for i in range(len(first_names)):
        user = Users()
        user.first_name = first_names[i]
        user.last_name = last_names[i]
        user.login = user.first_name.lower()
        user.email = user.login + "@example.com"
        user.password = generate_password_hash(''.join(random.choice(string.ascii_lowercase + string.digits) for i in range(10)))
        db.session.add(user)

    db.session.commit()
    return


